package iiet.constants;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import college.constants.Constants;
import college.dao.Attendance;
import college.dao.AttendanceId;
import college.dao.Branch;
import college.dao.Student;
import college.exception.SaveException;
import college.model.AttendanceFormModel;
import college.service.CollegeService;
import college.util.ExcelFileGenerator;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

	@Autowired
	CollegeService collegeService;

	@RequestMapping(value = "/branchform")
	public String branchForm(@ModelAttribute("branch") Branch branch) {
		System.out.println("HomeController: Passing through branchform...");
		return "branchform";
	}
	
	@RequestMapping(value = "/generateexcel")
	public String generateExcel(HttpServletRequest request,Model model) {
		
		
		
				/*String filename =  path to a file 

				File file = new File(filename);

				response.setContentType(new MimetypesFileTypeMap().getContentType(file));
				response.setContentLength((int)file.length());
				response.setHeader("content-disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));

				InputStream is = new FileInputStream(file);
				FileCopyUtils.copy(is, response.getOutputStream());

				return null;
*/
		
		
		
		List<Attendance> attendanceList = (List<Attendance>)request.getSession().getAttribute("attendanceList");
		System.out.println("HomeController: Passing through generateexcel...");
		String[] headings = Constants.headings;
		Object data[][] = new Object[attendanceList.size()][headings.length];
		int i=0;
		for(Attendance attendance : attendanceList) {
			data[i] = new Object[]{i++ , attendance.getId().getStudent().getHtno(),attendance.getId().getStudent().getName(),attendance.getAttendance() }; 
		}
		
		ExcelFileGenerator.createExcelFile("attendace.xls", headings, data); 
		model.addAttribute("attendanceList", attendanceList);
		return "attendancereport";
	}
	@RequestMapping(value = "/home")
	public String home() {
		System.out.println("HomeController: Passing through home......");
		return "home";
	}

	@RequestMapping(value = "/savebranch")
	public String saveBranch(@ModelAttribute("branch") Branch branch,
			Model model) {
		System.out.println("HomeController: Passing through savebranch...");
		try {
			collegeService.saveBranch(branch);
		
			model.addAttribute("successMessage", Constants.SAVED_SUCCESSFULLY);
		} catch (SaveException exception) {
			model.addAttribute("errorMessage", exception.getErrorMessage());
		}

		return "branchform";
	}

	@RequestMapping(value = "/studentform")
	public String studentForm(@ModelAttribute("student") Student student,
			Model model) {
		System.out.println("HomeController: Passing through studentform...");
		model.addAttribute("branchList", collegeService.findAllBranches());

		return "studentform";
	}

	@RequestMapping(value = "/savestudent")
	public String saveStudent(@ModelAttribute("student") Student student,
			BindingResult bindingResult, Model model) {
		System.out.println("HomeController: Passing through savestudent...");
		try {
			student.getContactDetails().setCid(student.getHtno().toUpperCase());
			student.getContactDetailses().add(student.getContactDetails());
			collegeService.saveStudent(student);
			model.addAttribute("successMessage", Constants.SAVED_SUCCESSFULLY);
		} catch (SaveException exception) {
			model.addAttribute("errorMessage", exception.getErrorMessage());
		}
		// ModelAndView mv = new ModelAndView("studentform", "command",
		// student);
		// mv.addObject("branchList", collegeService.findAllBranches());
		model.addAttribute("branchList", collegeService.findAllBranches());
		return "studentform";
	}

	@RequestMapping(value = "/attendanceform")
	public String attendanceForm(
			@RequestParam("branch") String branchCode, @RequestParam("year") String year, @RequestParam("sem") String sem,  @ModelAttribute("attendanceFormModel") AttendanceFormModel attendanceFormModel,
			Model model) {
		System.out.println("HomeController: Passing through attendanceform...");
		// List<Attendance> attendenceList = new ArrayList<Attendance>();
		model.addAttribute("studentList", collegeService.findAllstudents(branchCode, year, sem));
		// model.addAttribute("attendenceList", attendenceList);
		// model.addAttribute("attendance", new Attendance());
		return "attendanceform";
	}

	@RequestMapping(value = "/saveattendance")
	public String saveAttendance(
			@ModelAttribute("attendanceFormModel") AttendanceFormModel attendanceFormModel,
			Model model) {
		System.out
				.println("HomeController: Passing through savesattendance...");
		
		List<Attendance> alist = new ArrayList<Attendance>();
		for (Attendance attendance : attendanceFormModel.getAttendanceList()) {
			try {
				try {
					Date d = new SimpleDateFormat("dd-MM-yyyy")
							.parse(attendanceFormModel.getDate());
					if (attendance.getId() != null) {
						Student student = attendance.getId().getStudent();
						// student.setHtno(htno)
						AttendanceId id = new AttendanceId(d,
								attendanceFormModel.getHour(), student);
						attendance.setId(id);
						attendance.setFaculty(attendanceFormModel.getFaculty());
						attendance.setSubject(attendanceFormModel.getSubject());
						// attendance.setAttendance(attendanceFormModel.get)
						alist.add(attendance);
					}
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				model.addAttribute("successMessage",
						Constants.SAVED_SUCCESSFULLY);
			} catch (SaveException exception) {
				model.addAttribute("errorMessage", exception.getErrorMessage());
			}

		}
		collegeService.saveAttendance(alist);
		model.addAttribute("studentList", collegeService.findAllstudents());
		return "attendanceform";
	}
	@RequestMapping(value = "/attendancesearchform")
	public String attendanceSearchForm(
			@ModelAttribute("attendanceFormModel") AttendanceFormModel attendanceFormModel,
			Model model) {
		System.out.println("HomeController: Passing through attendancesearchform...");
		// List<Attendance> attendenceList = new ArrayList<Attendance>();
		//model.addAttribute("studentList", collegeService.findAllstudents());
		// model.addAttribute("attendenceList", attendenceList);
		// model.addAttribute("attendance", new Attendance());
		return "attendancesearchform";
	}
	
	@RequestMapping(value = "/searchattendance")
	public String searchAttendance(@RequestParam("date") String date, @RequestParam("hour") String hour, Model model) {
		System.out.println("HomeController: Passing through searchattendance...");
		List<Attendance> attendanceList = null;
		try {
			attendanceList = collegeService.findAttendance(date, hour);
			//attendanceList = collegeService.findAllAttendance();
			model.addAttribute("successMessage", Constants.SAVED_SUCCESSFULLY);
		} catch (SaveException exception) {
			model.addAttribute("errorMessage", exception.getErrorMessage());
		}
		
		
		model.addAttribute("attendanceList", attendanceList);
		model.addAttribute("date", date);
		model.addAttribute("hour", hour);
		return "attendancereport";
	}
	@RequestMapping(value = "/loginform")
	public String loginForm() {
		System.out.println("HomeController: Passing through loginform...");
		return "login";
	}
	@RequestMapping(value = "/attendance")
	public String attendance() {
		System.out.println("HomeController: Passing through loginform...");
		return "attendance";
	}
	
	
	
	@RequestMapping(value = "/download")
	public String download(HttpServletRequest request, HttpServletResponse response) {
		//int id = ServletRequestUtils.getRequiredIntParameter(request, "id");

	    File file = new File("c:\\student.xls");
	    response.setContentLength(new Long(file.length()).intValue());
        response.setHeader("Content-Disposition","attachment; filename=student.xls");
        
		try {
			
			OutputStream out = response.getOutputStream();
	        //response.setContentType("text/plain; charset=utf-8");
	        response.setContentType("application/xls"); //in my example this was an xls file
	        FileInputStream fi = new FileInputStream(file);
	        IOUtils.copy(fi, out);
	        out.flush();
	        out.close();


		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
	    
	   

	    return null;
	}
	
	
}